<?php

require_once APPLICATION_PATH . '/configs/config.php';

class UserController extends Uuch_BaseController {

    const COOKIE_NAME_BINDID='__XXBID__';

    /**
     * 为兼容以前的程序，在这个ID之前的联合登录用户，直接修改EMAIL，这个ID之后，所用绑定模式
     */
    const NOT_BIND_MAX_USERID=17375;

    public function indexAction() {
        
    }

    /**
     * 退出
     */
    public function logoutAction() {
        $this->setUser('');
        $this->_redirect('/');
    }

    /**
     * 找回密码第一步，验证用户名、邮箱、验证码
     */
    public function retakepasswordAction() {
        $ret['ret'] = 0;

//		$this->appendCss('/css/Share.css');
        $this->appendCss('/css/member/register.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $request = $this->getRequest();

        if ($request->isPost()) {
            //提交

            $email = $request->getParam('email');
            $userInfo = Application_Model_User::getByEmail($email);

            $ret['ret'] = -1;

            if ($userInfo == NULL) {
                $ret['ret'] = -255;
            } else {
                $userid = $userInfo->Id;

                $key = md5(md5($userid . time()) * rand(10000, 99999));

                $userKey = Application_Model_UserKey::getByUserId($userid);
                if ($userKey == null) {
                    $userKey = new Application_Model_UserKey();
                }
                $userKey->uid = $userid;
                $userKey->PwdKey = $key;
                $userKey->PwdTime = date('Y-m-d 00:00:00', time() + 3600 * 24 * 1); //结束时间为第二天0点
                $userKey->save();

                //发送注册邮件
                $link = "http://www.uuch.com/user/retakepasswordthree/uid/$userid/key/$key";

                $receive = array('email' => $email, 'name' => $email);

                $_SESSION['current_email'] = $email;

                $this->sendUserResetPasswordMail($receive, $link);

                $ret['ret'] = 1;
            }
            echo json_encode($ret);

            exit;
        }
    }

    /**
     * 找回密码第二步
     */
    public function retakepasswordtwoAction() {
        //$this->appendCss('/css/Share.css');
        $this->appendCss('/css/member/register.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $email = $_SESSION['current_email'];
        $emailName = Uuch_Mail::getEmailName($email);

        $emailUrl = Uuch_Mail::getEmailLoginUrl($emailName);

        $this->view->emailUrl = $emailUrl;
    }

    public function retakepasswordthreeAction() {
        //$this->appendCss('/css/Share.css');
        $this->appendCss('/css/member/register.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $ret["ret"] = 0;

            $uid = $request->getParam('uid');
            $pwd = $request->getParam('password1');

            $user_item = Application_Model_User::getByUserId($uid);
            $user_item->password = $user_item->generatePassword($pwd, $user_item->passwordsalt);

            $user_item->save();

            $ret["ret"] = 1;

            echo json_encode($ret);
            exit;
        } else {
            $uid = $request->getParam('uid');
            $key = $request->getParam('key');

            $flag = -1;  //-1,Key不对
            $error = '验证码不正确';

            $userKey = Application_Model_UserKey::getByUserId($uid);
            if (strcmp($userKey->PwdKey, $key) == 0) {
                if (strtotime($userKey->PwdTime) > time()) {
                    $flag = 1;  //正确
                    $error = '';
                } else {
                    $flag = -2;  //已过期
                    $error = '验证码已过期';
                }
            }

            $this->view->flag = $flag;
            $this->view->error = $error;
            $this->view->uid = $uid;
        }
    }

    public function retakepasswordfourAction() {
        //$this->appendCss('/css/Share.css');
        $this->appendCss('/css/member/register.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');
    }

    /**
      用户登录
     */
    public function loginAction() {
        $this->setTitle('用户登录');
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js');
        $this->appendCss('/css/member/login.css');

        //
        $request = $this->getRequest();

        if ($request->isPost()) {//提交登录
            $form = new Application_Form_Login();
            if ($form->isValid($request->getPost())) {
                $user = new Application_Model_User($form->getValues());
                $auth = Zend_Auth::getInstance();
                $auth->setStorage(new My_Auth_Storage_Cookie());

                $email = $form->getValue('email');
                $remember = $request->getParam('remember');

                //实例化验证对象
                $adapter = new MyAuthAdapter($form->getValue('email'), $form->getValue('password'));

                $result = $auth->authenticate($adapter); //登录验证

                switch ($result->getCode()) {
                    case Zend_Auth_Result::SUCCESS:
                        //保存登录记录
                        $UserItem = Application_Model_User::getByEmail($email);
                        if($UserItem->lastLogin < date("Y-m-d")){
                            $accountItem = Application_Model_UserAccount::addAccount($UserItem->Id);
                            $accountItem->TaskExchangeScore(Application_Model_Task::TASK_LOGIN);
                        }
                        $UserItem->lastLogin = date('Y-m-d H:i:s');
                        $UserItem->logintimes = $UserItem->logintimes + 1;
                        $UserItem->loginip = $_SERVER['REMOTE_ADDR'];
                        $UserItem->save();
                        $UserItem->getbyip();
                        $remember = $request->getParam("remember");
                        $this->setUser($email, $remember);

                        $user = Application_Model_User::getByEmail($email);
                        Application_Model_Cart::updateCart($user->Id);

                        $returnUrl = $this->getRequest()->getParam('returnUrl');

                        if (!$returnUrl)
                            $returnUrl = '/member/home';

                        $this->_redirector = $this->_helper->getHelper('Redirector');
                        $this->_redirect($returnUrl);
                        //$this->_redirector->gotoUrl('/member/home');
                        $this->view->flag = 'pass'; //暂时用

                        break;
                    default:
                        $this->view->flag = 'nopass';
                        $form->addErrorMessage('用户名或密码错误！');
                        break;
                }
            }
            $this->view->form = $form;
        }
    }

    /**
      注册用户信息
     */
    public function joinAction() {
        $this->view->title = "注册用户";
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js');
        $this->appendCss('/css/member/register.css');

        $form = new Application_Form_Join();
        $request = $this->getRequest();
        $this->view->form = $form;
        
        if (!$request->isPost()) {
            return;
        }
        if(!$form->isValid($request->getPost())){
            return;
        }

        //检测用户与邮箱是否存在
        if (Application_Model_User::getByEmail($form->getValue('email'))) {
            $this->view->message = '您的邮箱已经被注册了,请换一个邮箱或找回密码.';
            return;
        }

        $user = new Application_Model_User();
        $user->Email = $this->getSafeParam('email');
        $user->Nikename = $this->getSafeParam('nikename');

        $user->passwordsalt = rand(100000, 999999);
        $user->password = $user->generatePassword($this->getSafeParam('password'), $user->passwordsalt);
        $user->datecreated = date('Y-m-d H:i:s');
        $user->loginip = $_SERVER['REMOTE_ADDR'];
        $user->logintimes = 1;
        $user->lastLogin = date('Y-m-d H:i:s');
        $user->userLevel = 0;
        $user->UserType = 0;
        $user->State = 0;  //用户状态
        if(array_key_exists(Uuch_Util::COOKIE_NAME_RECOMMENDER, $_COOKIE)){
            $user->RecommendId = Uuch_Util::decryptString($_COOKIE[Uuch_Util::COOKIE_NAME_RECOMMENDER]);
        }
        if (array_key_exists(parent::COOKIE_SOURCE, $_COOKIE))
            $user->Source = $_COOKIE[parent::COOKIE_SOURCE];
        $user->save();
        
        if(array_key_exists(Uuch_Util::COOKIE_NAME_RECOMMENDER, $_COOKIE)){
            Application_Model_Recommend::addRecommend($user->Id, $user->RecommendId);
        }
        
        //生成仓库地址保存
        $user->storeno = Uuch_Util::getShortNum($user->id, 4);
        $user->save();

        $cityName = $user->getbyip();
        $cityItem = Application_Model_city::getByName($cityName);
        if($cityItem){
            $user->cityId = $cityItem->id;
        }else{
            $user->cityId = 10000;
        }
        $user->save();

        $uid = $user->id;
        $emailKey = md5($uid . time() . rand(100000, 999999));
        $emailTime = date('Y-m-d 00:00:00', time() + 3600 * 24 * 1);  //1天后过期

        $userKey = new Application_Model_UserKey();
        $userKey->Uid = $uid;
        $userKey->EmailKey = $emailKey;
        $userKey->EmailTime = $emailTime;
        $userKey->save();
        
        $this->setUser($form->getValue('email'), FALSE);
        $this->_redirect('/user/joinconfrim');
    }

    public function checkemailAction() {
        //检测邮箱是否存在
        $email = $this->getRequest()->getParam('email');
        if (Application_Model_User::getByEmail($email))
            $this->view->info = false;
        else
            $this->view->info = true;
    }

    public function checknikenameAction() {
        //检测昵称是否存在

        $nikename = $this->getRequest()->getParam('nikename');
        if (Application_Model_User::getbynikename($nikename))
            $this->view->info = false;
        else
            $this->view->info = true;
    }

    public function joinconfrimAction() {
        $this->setTitle('注册成功!');
        $this->appendScript('/js/jquery.min.js');
        $this->appendCss('/css/member/register.css');
        $this->view->email = $this->currentUser()->Email;
        $this->view->nikeName = $this->currentUser()->Nikename;
        
        $this->view->emailUrl = Uuch_Mail::getEmailLoginUrl(Uuch_Mail::getEmailName($this->currentUser()->Email));
    }
    
    public function bindconfrimAction(){
        $this->setTitle('绑定成功!');
        $this->appendScript('/js/jquery.min.js');
        $this->appendCss('/css/member/register.css');
        $this->view->email = $this->currentUser()->Email;
        $this->view->nikeName = $this->currentUser()->Nikename;
        $this->view->emailUrl = Uuch_Mail::getEmailLoginUrl(Uuch_Mail::getEmailName($this->currentUser()->Email));
    }

    /**
     * 绑定用户
     * @return type
     */
    public function bindAction(){
        $this->setTitle('联合登录成功，请绑定Email');
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/jquery.validate.min.js')
                ->appendScript('/js/messages_cn.js');;
        $this->appendCss('/css/member/register.css');
        $bindUser = $this->getBindUser();
        
        if($bindUser == NULL){
            $this->redirect('login', 'user');
        }
        
        $this->view->unionName = $bindUser->userType;
        $this->view->nickName = $bindUser->nikename;
        if(!$this->isPost()){
            return;
        }

        $email = $this->getSafeParam('email');
        $emailUser = Application_Model_User::getByEmail($email);
        if($emailUser != NULL){
            $password = $this->_getParam('password');
            $this->view->email = $email;
            if($password==NULL || $password==''){
                $this->view->message = '该Email已经注册过了，不能重新绑定';
                $this->render('bindemail');
                return;
            }else{
                $gp = $emailUser->generatePassword($password, $emailUser->passwordsalt);
                if($gp == $emailUser->password){
                    $bindUser->bindId = $emailUser->Id;
                    $bindUser->save();
                    $this->setUser($emailUser->Email, FALSE);
                    $this->redirect('home', 'member');
                    return;
                }
                $this->render('bindemail');
            }
        }

        if($bindUser->Id < self::NOT_BIND_MAX_USERID){//如果是之前的用户，则直接修改EMAIl地址
            $bindUser->email = $email;
            $bindUser->save();
            $this->setUser($email, FALSE);
            $this->redirect('home', 'member');
            return;
        }
        $user = new Application_Model_User();
        $user->email = $email;
        $user->nikename = $bindUser->nikename;
        $user->realname = $bindUser->nikename;
        $user->datecreated = date('Y-m-d H:i:s');
        $user->passwordsalt = rand(100000, 999999);
        $user->password = $user->generatePassword(rand(100000, 999999), $user->passwordsalt);
        $user->username = $bindUser->nikename;
        $user->userLevel = 0;
        $user->lastLogin = date('Y-m-d H:i:s');
        $user->synKey = '';
        $user->userType = '';
        $user->logintimes = 1;
        $user->loginip = $_SERVER['REMOTE_ADDR'];
        $user->RecommendId = $bindUser->RecommendId;        
        $user->save();
        $user->getbyip();         //记录城市Id
        //生成仓库地址保存
        $user->storeno = Uuch_Util::getShortNum($user->id, 4);
        $user->save();
        $bindUser->bindId = $user->Id;
        $bindUser->save();
        $this->setUser($user->Email, FALSE);
        $this->redirect('home', 'member');
    }

    /**
     * 联合登录
     */
    public function unionAction(){
        $name = $this->getSafeParam('name');
        $union = Application_Model_UnionUser_Base::createUnion($name);
        $this->_redirect($union->getLoginUrl());
    }
    
    /**
     * 设置绑定用户ID
     * @param type $bindId
     */
    private function setBind($bindId){
        setcookie(self::COOKIE_NAME_BINDID,  Uuch_Util::encryptString($bindId),time()+30*3600*24,'/');
    }
    
    protected $_binder;
    /**
     * 返回绑定用户
     * @return Application_Model_User
     */
    public function getBindUser(){
        if($this->_binder != NULL){
            return $this->_binder;
        }
        if(!array_key_exists(self::COOKIE_NAME_BINDID, $_COOKIE)){
            return null;
        }
        $bindId = Uuch_Util::decryptString($_COOKIE[self::COOKIE_NAME_BINDID]);
        return Application_Model_User::load($bindId);
    }
    
    private function bindUserInfo($uuchUser){
        $bindUser = $uuchUser->getBindUser();
        if($bindUser == null && $uuchUser->id <= self::NOT_BIND_MAX_USERID){
            if(preg_match('/^uuch\w+@uuch.com$/', $uuchUser->email)){  
                $uuchUser->lastLogin = date('Y-m-d H:i:s');
                $uuchUser->logintimes = $uuchUser->logintimes + 1;
                $uuchUser->loginip = $_SERVER['REMOTE_ADDR'];
                $uuchUser->save();
                $this->setBind($uuchUser->Id);
                $this->redirect('bind', 'user');
            }else{
                $bindUser = $uuchUser;
            }
        }else{
            if($bindUser == NULL){
                $this->setBind($uuchUser->Id);
                $this->redirect('bind', 'user');
            }    
        }

        $bindUser->lastLogin = date('Y-m-d H:i:s');
        $bindUser->logintimes = $bindUser->logintimes + 1;
        $bindUser->loginip = $_SERVER['REMOTE_ADDR'];
        $bindUser->save();

        $this->setUser($bindUser->email, FALSE);
        $this->redirect('home', 'member');        
    }

    /**
     * 回掉
     * @param type $name
     * @return type
     * @throws ErrorException
     */
    public function callback($name){
        $union = Application_Model_UnionUser_Base::createUnion($name);
        if(!$union->isValid()){
            throw new ErrorException('抱歉！联合登录不能通过验证,请联系客服。');
        }
        
        $uuchUser = Application_Model_User::getByKey($union->getUserKey());
        if($uuchUser){
            $this->bindUserInfo($uuchUser);
            return;
        }
        
        $userInfo = $union->getUserInfo();
        if($userInfo==NULL){
            throw new ErrorException('抱歉！获取用户信息失败，请联系客服。');
        }
        $user = new Application_Model_User();
        $user->email = 'uuch' . uniqid() . '@uuch.com';
        $user->nikename = $userInfo->nickname;
        $user->realname = $userInfo->nickname;
        $user->datecreated = date('Y-m-d H:i:s');
        $user->passwordsalt = rand(100000, 999999);
        $user->password = $user->generatePassword(rand(100000, 999999), $user->passwordsalt);
        $user->username = $userInfo->nickname;
        $user->userLevel = 0;
        $user->lastLogin = date('Y-m-d H:i:s');
        $user->synKey = $userInfo->userKey;
        $user->userType = $union->getUnionName();
        $user->logintimes = 1;
        $user->loginip = $_SERVER['REMOTE_ADDR'];
        if(array_key_exists(Uuch_Util::COOKIE_NAME_RECOMMENDER, $_COOKIE)){
            $user->RecommandId = Uuch_Util::decryptString($_COOKIE[Uuch_Util::COOKIE_NAME_RECOMMENDER]);
        }
        $user->save();

        //生成仓库地址保存
        $user->storeno = Uuch_Util::getShortNum($user->id, 4);
        $user->save();
        $this->setBind($user->Id);
        $this->redirect('bind', 'user');
    }

    /**
     * qq异步登录接口
     */
    public function qqsynconnectAction() {
        $this->callback('qq');
    }
    
    /**
     * 联合登录回调接口
     */
    public function unioncallbackAction(){
        $name = $this->_getParam('name');
        $this->callback($name);
    }

    public function facebookAction(){
        $fb =new Application_Model_UnionUser_facebook();
        $url = $fb->getfbUrl();
        $this->_redirect($url);
        
    }
    
    public function alipayAction() {
        require_once APPLICATION_PATH . '/configs/login/alipay/alipay.config.php';
        require_once APPLICATION_PATH . '/configs/login/alipay/lib/alipay_service.class.php';

        $anti_phishing_key = '';

        $exter_invoke_ip = '';

        //构造要请求的参数数组
        $parameter = array(
            "service" => "alipay.auth.authorize",
            "target_service" => 'user.auth.quick.login',
            "partner" => trim($aliapy_config['partner']),
            "_input_charset" => trim(strtolower($aliapy_config['input_charset'])),
            "return_url" => trim($aliapy_config['return_url']),
            "anti_phishing_key" => $anti_phishing_key,
            "exter_invoke_ip" => $exter_invoke_ip
        );

        //构造快捷登录接口
        $alipayService = new AlipayService($aliapy_config);
        $html_text = $alipayService->alipay_auth_authorize($parameter);

        echo $html_text;
        exit;
    }

    public function sendUserResetPasswordMail($receive, $link) {
        $title = "重置密码";
        $body = "尊敬的悠奇用户：

					您好！
				
					您的密码重设要求已经得到验证。请点击以下链接输入您新的密码：
				
					(pleae click on the following link to reset your password:)
				
					$link
				
					如果您的email程序不支持链接点击，请将上面的地址拷贝至您的浏览器(例如IE)的地址栏进入悠奇。
				
					感谢对悠奇的支持。
				
					悠奇 http://www.uuch.com/
				
					(这是一封自动产生的email，请勿回复。)
				";

        return Uuch_Mail::SendMail($title, $body, $receive);
    }

    public function activeAction() {
        $uid = $this->getSafeParam("uid");

        $emailKey = $this->getSafeParam("MjkzNzM");

        if (!empty($uid) && !empty($emailKey)) {

            $userKey = Application_Model_UserKey::getByUserId($uid);

            $_emailTime = $userKey->EmailTime;

            $_emailKey = $userKey->EmailKey;

            if (strcmp($emailKey, $_emailKey) == 0) {

                $userInfo = Application_Model_User::load($uid);
                if($userInfo->State == 0){
                    $accountItem = Application_Model_UserAccount::addAccount($uid);
                    $accountItem->AttestEmail();
                    if($userInfo->RecommendId != null && $userInfo->RecommendId != "") {
                        $accountItemB = Application_Model_UserAccount::addAccount($userInfo->RecommendId);
                        $accountItemB->TaskExchangeScore("recommend");
                        $recommendItem = Application_Model_Recommend::ByUserIdReUserId($uid, $userInfo->RecommendId);
                        $recommendItem->IsAbled = Application_Model_Recommend::IsAbled_Complete;
                        $recommendItem->save();
                    }
                }
                $userInfo->State = 1;

                $userInfo->save();

                $this->setUser($userInfo->Email, FALSE);
                $this->_redirector = $this->_helper->getHelper('Redirector');
                $this->_redirector->gotoUrl('/member/home');
            } else {
                //EmailKey不正确
                echo 'EmailKey不正确';
            }
        }


        //print_r($userKey);

        exit;
    }
}

class MyAuthAdapter implements Zend_Auth_Adapter_Interface {

    protected $_email;
    protected $_password;

    public function __construct($email, $password) {
        $this->_email = $email;
        $this->_password = $password;
    }

    public function authenticate() {

        $email = $this->_email;
        if (strlen($email) > 6 && preg_match("/^[\\w\\-\\.]+@[\\w\\-]+(\\.\\w+)+$/", $email))
            $user = Application_Model_User::getByEmail($this->_email); //email登录
        else
            $user = Application_Model_User::getbyusername($this->_email); //用户名登录

        if (NULL == $user)
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, "用户邮箱不存在");

        $password = $user->generatePassword($this->_password, $user->Passwordsalt);
        if ($password == $user->Password) {
            return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user->username);
        }

        return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_UNCATEGORIZED, "密码错误");
    }

}

/**
 * A cookie-based Zend_Auth storage backend that does not require sessions
 *
 */
class My_Auth_Storage_Cookie implements Zend_Auth_Storage_Interface {

    /**
     * @var string
     */
    protected $_basedir = '/';

    /**
     * @var string
     */
    protected $_cookieName;

    /**
     * @var string
     */
    protected $_domain;

    /**
     * @var string
     */
    protected $_secret;

    /**
     * @var mixed
     */
    protected $_cached;

    /**
     * Constructor
     *
     * @param string $cookieName The name of the cookie where the identity is stored
     * @param string $secret The salt used in the hashing of the data
     */
    public function __construct($cookieName = null, $secret = null) {
        if (null !== $cookieName) {
            $this->setCookieName($cookieName);
        }

        if (null !== $secret) {
            $this->setSecret($secret);
        }
    }

    /**
     * The basedir of the cookie
     *
     * @return string
     */
    public function getBasedir() {
        return $this->_basedir;
    }

    /**
     * Set the basedir of the cookie
     *
     * @param string $basedir
     * @return Portal_Auth_Storage_Cookie
     */
    public function setBasedir($basedir) {
        $this->_basedir = $basedir;
        return $this;
    }

    /**
     * Get the name of the cookie
     *
     * @return string
     */
    public function getCookieName() {
        return $this->_cookieName;
    }

    /**
     * Set the name of the cookie
     *
     * @param string $cookieName
     * @return Portal_Auth_Storage_Cookie
     */
    public function setCookieName($cookieName) {
        $this->_cookieName = $cookieName;
        return $this;
    }

    /**
     * Get the (sub)domain the cookie is set for
     *
     * @return string
     */
    public function getDomain() {
        return $this->_domain;
    }

    /**
     * Set the (sub)domain the cookie is set for
     *
     * @param string $domain
     * @return Portal_Auth_Storage_Cookie
     */
    public function setDomain($domain) {
        $this->_domain = $domain;
        return $this;
    }

    /**
     * Get the Secret (or salt) used to store the data
     *
     * @return string
     */
    public function getSecret() {
        return $this->_secret;
    }

    /**
     * Set Secret (or salt) used to store the data
     *
     * @param string $secret
     * @return Portal_Auth_Storage_Cookie
     */
    public function setSecret($secret) {
        $this->_secret = $secret;
        return $this;
    }

    /**
     * Returns true if and only if storage is empty
     *
     * @throws Zend_Auth_Storage_Exception If it is impossible to determine whether storage is empty
     * @return boolean
     */
    public function isEmpty() {
        return $this->read() == null;
    }

    /**
     * Returns the contents of storage
     *
     * Behavior is undefined when storage is empty.
     *
     * @throws Zend_Auth_Storage_Exception If reading contents from storage is impossible
     * @return mixed
     */
    public function read() {
        if (!$this->_cached) {

            if (array_key_exists($this->_cookieName, $_COOKIE)) {
                $value = $_COOKIE[$this->_cookieName];

                list ($contents, $now, $checksum) = explode('|', $value);

                if (md5(base64_decode($contents) . $now . $this->_secret) == $checksum) {
                    $this->_cached = $contents;
                }
            }
        }

        return $this->_cached;
    }

    /**
     * Writes $contents to storage
     *
     * @param  mixed $contents
     * @throws Zend_Auth_Storage_Exception If writing $contents to storage is impossible
     * @return void
     */
    public function write($contents) {
        $this->_cached = $contents;

        $now = time();
        $checksum = md5($contents . $now . $this->_secret);
        $value = base64_encode($contents) . '|' . $now . '|' . $checksum;

        if (!setcookie($this->getCookieName(), $value, 0, // end of the session
                        $this->getBasedir(), $this->getDomain(), null, // https
                        null)) {
            throw new Zend_Auth_Storage_Exception('Failed to set cookie');
        }
    }

    /**
     * Clears contents from storage
     *
     * @throws Zend_Auth_Storage_Exception If clearing contents from storage is impossible
     * @return void
     */
    public function clear() {
        if (!setcookie($this->_cookieName, false, // clears the cookie
                        0, $this->getBasedir())) {
            throw new Zend_Auth_Storage_Exception('Failed to clear cookie');
        }
    }

}